<!--页面 -->
<template>
	<div>
		<audio id="chatAudio">
		<source src="../../assets/voice/notify.ogg" type="audio/ogg">
		<source src="../../assets/voice/notify.mp3" type="audio/mpeg">
		<source src="../../assets/voice/notify.wav" type="audio/wav">
		</audio>
	</div>
</template>

<script>
	import Vue from 'vue'
	export default {
		props: {
		    connectNums: {
		      type:Number,
		      default:1
		    },
		},
		data(){
			return {
				isdebounce:true,  // 闪烁防抖处理
				is_open_socket:false,
				websocket: null,
				pingInterval:30,
				manMade:true,
				connectNum:1,
				//心跳检测
				timeout : 20000,//多少秒执行检测
				heartbeatInterval : null, //检测服务器端是否还活着
				reconnectTimeOut : null, //重连之后多久再次重连
			}
		},
		methods:{
			initWebSocket() { //初始化websocket
			    const WS_URI = this.apifun.wsssite;
			    this.websocket = new WebSocket(WS_URI);
			    this.start();
				
			    this.is_open_socket = true;
			    this.websocket.onmessage = this.websocketOnMessage;
			    this.websocket.onclose = this.websocketClose;
				this.websocket.close = this.close;
			    Vue.prototype.$websocket = this.websocket;
			    this.$store.state.wsStatus = true;
			},
			websocketOnMessage(e) { //数据接收
			    const data = JSON.parse(e.data);
				const datas = data.data;
				let userInfo = JSON.parse(localStorage.getItem('userInfo'));
				let token = localStorage.getItem('token')
				
			    switch (data['type']) {
			        case 'ping':
			            this.websocketSend({type:"pong"});
			            break;
					case 'pong':  // 心跳回应
						break;
			        case 'init':  // 登录 更新用户列表
						localStorage.setItem('client_id',data.client_id)
						this.websocketSend({
						    "type": "bindUid",
							"token":token,
							// "user_id":userInfo.user_id
						});
			            break;
					case 'isOnline':    // 改变状态 0离线1在线、2忙碌
						this.$store.state.appendMessage = data;
						break;
					case "offline":  //异地登录
						let clientId = localStorage.getItem('client_id');
						break;
					case 'simple':  // 一对一消息   （new_order：订单更新）
					case 'webrtc':    // 语音通话
					case 'group' :  // 群消息  [此项目用不到]
						datas.parenttype = data.type;  // 父级type
						if(datas.parenttype == 'webrtc'){
							this.electron.ipcRenderer.send("appendMessage",data)  // 向正在语音中的通话进行推送消息
						};
						if(datas.parenttype != 'webrtc'){
							if (datas.from_user != userInfo.user_id) {  // 有新消息
								// 防抖处理（防止消息同时来多条时一直闪）
								if(this.isdebounce){
									this.isdebounce=false;
									this.electron.ipcRenderer.send('flashFrame');  // 缩小闪（下部图标）
									this.electron.ipcRenderer.send('starfun');  // 关闭后右下角图标闪
									setTimeout(()=>{
										this.isdebounce=true;
									},2000)
								}
								// const contact = this.getContact(datas.toContactId);
								// 如果开启了声音才播放
								// if (data.toContactId == 'system' || contact.is_notice == 1) {  // //播放声音或震动
								// }
							}
						};
						this.$store.state.appendMessage = data;
						// this.$emit('appendMessage', data)  // 目前使用vuex传递数据
						break;
					case 'undoMessage':
						this.$store.state.appendMessage = data;
						break;
					case 'setChatTop':  //更新联系人
						break;
					case "setIsNotice":
						break;
			        default:
						this.$store.commit('catchSocketAction', datas);
			            break;
			    }
			},
			websocketClose(e) {  //关闭 (下线)
				this.is_open_socket = false;
				clearInterval(this.heartbeatInterval)  // 关闭连接
				clearInterval(this.reconnectTimeOut)  // 关闭重连
				if (this.connectNum < 3) {
					this.manMade = false
					this.reconnect();  // 重连
					this.connectNum += 1
			        return;
				} else {
			        this.$store.state.wsStatus = false;
					this.connectNum = 1;
			        this.websocket = null
				}
				// 下线请求
			},
			start() {
			    this.heartbeatInterval = setInterval(() => {
			        this.websocketSend({
			            "type": "ping"
			        });
			    }, this.timeout)
			},
			websocketSend(agentData) { //数据发送 bindUid、pong
			    var data=JSON.stringify(agentData);
			    if(this.checkStatus && this.websocket){
					if(this.websocket.readyState === this.websocket.OPEN){
						this.websocket.send(data);
					}else{  //未开启或正在开启
						setTimeout(()=>{
							this.websocketSend(agentData)
						},1000)
					}
				}
			},
			checkStatus(){  // 0尚未建立 1已建立 2进行关闭  3已经关闭或没建立
			    if(!this.websocket || [2,3].includes(this.websocket.readyState)){
			        console.log("未链接！")
			        return false;
			    }
			    return true;
			},
			close() {
			    if (!this.is_open_socket) {
			        return
			    }
			    this.websocket.close();
			},
			reconnect(){
			    console.log('reconnect',"正在重连...");
			    //停止发送心跳
			    clearInterval(this.heartbeatInterval)
			    //如果不是人为关闭的话，进行重连
			    if (!this.is_open_socket && this.manMade == false ) {
			        console.log("5秒后重新连接...")
			        this.reconnectTimeOut = setInterval(() => {
			            this.initWebSocket();
			        }, 5000)
			    }
			},
			// ----功能函数
			playAudio () {  // 提示音
			    const audio = document.getElementById('chatAudio');
			    audio.currentTime = 0;   // 从头播放
			    audio.play();
			},
			getContact(id) {
				let contacts = JSON.parse(localStorage.getItem('allContacts'));
				if (!id) {
					return contacts;
				} else {
					const contact = contacts.find(obj => obj.id == id);
					return contact;
				}
			}
		},
		created() {
			// if(this.connectNums != 0){
			// 	this.connectNum = this.connectNums;
			// }
		    this.initWebSocket()
		},
	}
</script>